package com.sgb.kjwl.view.ui.fragment.pick;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentPickAttentionNoticingBidBinding;
import com.sgb.kjwl.di.pick.DaggerPickProjectComponent;
import com.sgb.kjwl.di.pick.PickProjectModule;
import com.sgb.kjwl.model.entity.pick.PreNoticeItemEntity;
import com.sgb.kjwl.view.ui.activity.pick.PickNoticeBidDetailActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickWinningNoticeAdapter;
import com.sgb.kjwl.view.widget.CommonCategoryFilterPopWindow;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.sgb.kjwl.viewmodel.pick.PickAttentionNoticingBidModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 智能关注-招采-中标公告
 */
public class PickAttentionNoticingBidFragment extends AppFragment {

    private boolean isMore = false;
    private PickWinningNoticeAdapter adapter;

    private boolean isChangeMoney;
    private boolean isChangeType;
    private boolean isChangeSort;

    private PickHallBidingPopWindow pickSortPopWindow;
    private CommonCategoryFilterPopWindow categoryFilterPopWindow;
    private PickHallBidingPopWindow pickMoneyPopWindow;

    private List<PickSelectEntity> priceData = new ArrayList<>();
    private List<PickSelectEntity> provinceData = new ArrayList<>();
    private List<PickSelectEntity> cityData = new ArrayList<>();
    private List<PickSelectEntity> typeData = new ArrayList<>();
    private List<PickSelectEntity> sortData = new ArrayList<>();

    //排序类型
    private String sortType = "1";
    private String sortTypeName;
    //省
    private String areacode;
    private String areaName;
    //地区
    private String citysNos;
    private String goodsType;
    //中标金额
    private String pickMoney;
    private String pickMoneyName;
    //类型
    private String typeNos = "0";
    private String typeName;

    @Inject
    PickAttentionNoticingBidModel viewModel;
    private FragmentPickAttentionNoticingBidBinding binding;

    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;

    public static PickAttentionNoticingBidFragment newInstance() {
        PickAttentionNoticingBidFragment fragment = new PickAttentionNoticingBidFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pick_attention_noticing_bid, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPickProjectComponent
                .builder()
                .appComponent(appComponent)
                .pickProjectModule(new PickProjectModule(this))
                .build()
                .inject(this);
    }

    private void initView() {

        adapter = new PickWinningNoticeAdapter(getActivity(), null);
        binding.noticeList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.noticeList.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.noticeList.setAdapter(adapter);
        binding.noticeList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isMore = false;
                viewModel.prepage.set(1);
                initFilterData();
            }

            @Override
            public void onLoadMore() {
                isMore = true;
                viewModel.prepage.set(viewModel.prepage.get() + 1);
                initFilterData();
            }
        });

        adapter.setOnItemClick(new AdapterOnItemClick<PreNoticeItemEntity>() {
            @Override
            public void onItemClick(PreNoticeItemEntity goodsInfoEntity3, int position) {
                //中标
                PickNoticeBidDetailActivity.start(getActivity(), goodsInfoEntity3.getTenderNo() + "");
            }
        });

    }

    private void initFilterData() {
        viewModel.getBidedData(typeNos, pickMoney, areacode, citysNos, sortType, goodsType);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sort:
                showSortPopWindow();
                break;
            case R.id.tv_area:
                showProvincePopWindow();
                break;
            case R.id.tv_money:
                showMoneyPopWindow();
                break;
            case R.id.tv_category:
                if (null != typeData && typeData.size() > 0) {
                    if (TextUtils.isEmpty(typeName)) {
                        typeName = "招标类型";
                    }
                    updateChooseTextStatus(binding.tvCategory, TextUtils.isEmpty(typeNos) ? -1 : -2, typeName);
                    categoryFilterPopWindow.showPopWindow1(binding.tvCategory);
                    categoryFilterPopWindow.setData1(typeData, Integer.valueOf(typeNos), "",false);
                }
                break;
        }
    }

    /**
     * 分类
     */
    public void setTenderGoodsCategoryAllList(List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> datas) {
        categoryFilterPopWindow.setCategoryData(datas);
    }

    public void setPriceDatas(List<PickSelectEntity> datas) {
        priceData.clear();
        priceData.addAll(datas);
    }

    public void setSortDatas(List<PickSelectEntity> datas) {
        sortData.clear();
        sortData.addAll(datas);
    }

    public void setTypeDatas(List<PickSelectEntity> datas) {
        typeData.clear();
        typeData.addAll(datas);
    }

    public void setCityDatas(List<PickSelectEntity> data) {
        cityData.clear();
        cityData.addAll(data);
        mAddressPop.setData(scrData, false);
    }

    public void setProvinceDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(scrData, true);
        } else {
            viewModel.getAddressCityData(scrData, citysNos);
        }
    }

    /**
     * 中标金额
     */
    private void showMoneyPopWindow() {
        if (TextUtils.isEmpty(pickMoneyName)) {
            pickMoneyName = "中标金额";
        }
        updateChooseTextStatus(binding.tvMoney, TextUtils.isEmpty(pickMoney) ? -1 : -2, pickMoneyName);
        pickMoneyPopWindow.showPopwindow0(binding.tvMoney);
        pickMoneyPopWindow.setData(priceData);
    }

    /**
     * 省份
     */
    private void showProvincePopWindow() {
        if (TextUtils.isEmpty(areaName)) {
            areaName = "地区";
        }
        updateChooseTextStatus(binding.tvArea, TextUtils.isEmpty(areacode) && TextUtils.isEmpty(citysNos) ? -1 : -2, areaName);
        mAddressPop.showPopwindow0(binding.tvArea);
    }

    /**
     * 排序
     */
    private void showSortPopWindow() {
        if (TextUtils.isEmpty(sortTypeName)) {
            sortTypeName = "综合排序";
            pickSortPopWindow.setDefItem();
        }
        updateChooseTextStatus(binding.tvSort, TextUtils.isEmpty(sortType) ? -1 : -2, sortTypeName);
        pickSortPopWindow.showPopwindow0(binding.tvSort);
        pickSortPopWindow.setData(sortData, false);
    }

    private void initData() {

        binding.tvArea.setOnClickListener(this);
        binding.tvCategory.setOnClickListener(this);
        binding.tvMoney.setOnClickListener(this);
        binding.tvSort.setOnClickListener(this);

        categoryFilterPopWindow = new CommonCategoryFilterPopWindow(getActivity(), true);
        categoryFilterPopWindow.setBgView(binding.grayLayout);
        categoryFilterPopWindow.setResultListener(new CommonCategoryFilterPopWindow.Listener() {
            @Override
            public void setResultListener(String text, String result, String typeNo) {
                goodsType = result;
                typeNos = typeNo;
                typeName = text;
                if (!"全部".equals(typeName)) {
                    isChangeType = true;
                    updateChooseTextStatus(binding.tvCategory,1,typeName);
                }else{
                    isChangeType = false;
                    typeName = "招标类型";
                    updateChooseTextStatus(binding.tvCategory,0,typeName);
                }
                initFilterData();
            }

            @Override
            public void setResetResultListener() {
                goodsType = "0";
                typeNos = "0";
                typeName = "招标类型";
                isChangeType = false;
                updateChooseTextStatus(binding.tvCategory,0,typeName);
            }
        });
        categoryFilterPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeType) {
                    updateChooseTextStatus(binding.tvCategory,0,typeName);
                } else {
                    updateChooseTextStatus(binding.tvCategory,1,typeName);
                }
            }
        });
        categoryFilterPopWindow.setCategoryCallBack1(new CommonCategoryFilterPopWindow.CategoryCallBack1() {
            @Override
            public void resultPosition1(String posName1, String posName2, String posName3, String posName4, int pos1, int pos2, int pos3, int pos4) {

            }

            @Override
            public void setChildData(String position) {
                viewModel.getTenderGoodsCategoryAllList(position);
            }
        });
        // 金额
        pickMoneyPopWindow = new PickHallBidingPopWindow(getActivity());
        pickMoneyPopWindow.setBgView(binding.grayLayout);
        pickMoneyPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                pickMoney = ((PickSelectEntity) key1).getNo();
                pickMoneyName = ((PickSelectEntity) key1).getProjectscale();
                if (!"全部".equals(pickMoneyName)) {
                    isChangeMoney = true;
                    updateChooseTextStatus(binding.tvMoney,1,pickMoneyName);
                }else{
                    isChangeMoney = false;
                    pickMoneyName = "中标金额";
                    updateChooseTextStatus(binding.tvMoney,0,pickMoneyName);
                }
                initFilterData();
            }
        });
        pickMoneyPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeMoney) {
                    updateChooseTextStatus(binding.tvMoney,0,pickMoneyName);
                } else {
                    updateChooseTextStatus(binding.tvMoney,1,pickMoneyName);
                }
            }
        });
        pickMoneyPopWindow.setDefItem();
        //排序方式
        pickSortPopWindow = new PickHallBidingPopWindow(getContext());
        pickSortPopWindow.setBgView(binding.grayLayout);
        pickSortPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                sortType = ((PickSelectEntity) key1).getNo();
                sortTypeName = ((PickSelectEntity) key1).getProjectscale();
                if(!"综合排序".equals(sortTypeName)){
                    isChangeSort = true;
                    updateChooseTextStatus(binding.tvSort,1,sortTypeName);
                }else{
                    isChangeSort = false;
                    sortTypeName = "综合排序";
                    updateChooseTextStatus(binding.tvSort,0,sortTypeName);
                }
                initFilterData();
            }
        });
        pickSortPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeSort) {
                    updateChooseTextStatus(binding.tvSort,0,sortTypeName);
                } else {
                    updateChooseTextStatus(binding.tvSort,1,sortTypeName);
                }
            }
        });

        viewModel.getProvinceData();
        viewModel.getFilterTypeData();
        viewModel.getSortTypeData();
        viewModel.getSelecteScaleData();
        initFilterData();
        initAddressPopup();
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                areacode = entity.getProvinceNo();
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    areaName = entity.getProvinceName();
                    areacode = entity.getProvinceNo();
                    citysNos = "";
                    if ("0".equals(areacode)) {
                        areaName = "地区";
                    }
                    updateChooseTextStatus(binding.tvArea, 1, areaName);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        citysNos = entity.getCityNo();
                        areaName = entity.getCityName();
                        viewModel.getAddressCityData(scrData, citysNos);
                        updateChooseTextStatus(binding.tvArea, 1, areaName);
                    }
                } else {
                    areaName = "地区";
                    areacode = "";
                    citysNos = "";
                    updateChooseTextStatus(binding.tvArea, 0, areaName);
                }
                initFilterData();
            }
        });

        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvArea, "地区".equals(areaName) ? 0 : 1, areaName);
        });
    }

    public void getBiddingData(List<PreNoticeItemEntity> list) {
        binding.noticeList.refreshComplete();
        if (isMore) {
            binding.noticeList.loadMoreComplete();
            if (list.size() > 0) {
                adapter.addDatas(list);
            } else {
                binding.noticeList.setLoadingMoreEnabled(false);
            }
        } else {
            binding.noticeList.refreshComplete();
            if (list.size() > 0) {
                binding.empty.setVisibility(View.GONE);
                binding.noticeList.setVisibility(View.VISIBLE);
                adapter.setDatas(list);
                binding.noticeList.setLoadingMoreEnabled(true);
            } else {
                adapter.setDatas(new ArrayList<>());
                binding.noticeList.setVisibility(View.GONE);
                binding.empty.setVisibility(View.VISIBLE);
            }
        }
        adapter.notifyDataSetChanged();
    }

    public void empty() {
        if (null != adapter.getDatas() && adapter.getDatas().size() > 0) {
            binding.noticeList.loadMoreComplete();
        } else {
            binding.noticeList.setVisibility(View.VISIBLE);
            binding.empty.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 4) {
                name = name.substring(0, 4) + "...";
            }
        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333,true,name);
        }else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333,false,name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main,false,name);
        }
    }
}
